#!/bin/bash

setup_zsh() {
    zsh_path=$(which zsh)
    if [[ ${zsh_path} == "" ]]; then
        echo "error: no zsh found, stop zsh setup."
        return 255
    fi
    echo $(${zsh_path} --version)

    # Change the default shell to be zsh
    if [[ ! $(getent passwd $(whoami)) =~ "zsh" ]]; then
        chsh -s ${zsh_path}
        if [[ ! $(getent passwd $(whoami)) =~ "zsh" ]]; then
            echo "error: \"chsh -s ${zsh_path}\" failed."
            return 255
        fi
        echo "\"chsh -s ${zsh_path}\" done."
    else
        echo "zsh is the default shell."
    fi

    ## Install oh-my-zsh to enhance zsh
    if [[ ! -d "$HOME/.oh-my-zsh" ]]; then
        sh -c "$(wget https://raw.github.com/robbyrussell/oh-my-zsh/master/tools/install.sh -O -)"
        if [[ ! -d "$HOME/.oh-my-zsh" ]]; then
            echo "error: failed to download and install oh-my-zsh."
            return 255
        fi
    else
        echo "oh my zsh is already installed."
    fi
    sed -i "s/ZSH_THEME=\"\w*\"/ZSH_THEME=\"gallois\"/g" $HOME/.zshrc

    zsh_plugin_path=${ZSH_CUSTOM:-$HOME/.oh-my-zsh/custom}/plugins
    if [[ ! -d "${zsh_plugin_path}/zsh-autosuggestions" ]]; then
        git clone https://gitee.com/imirror/zsh-autosuggestions.git ${zsh_plugin_path}/zsh-autosuggestions
    else
        echo "plugin zsh-autosuggestions is already installed."
    fi
    if [[ $(grep -c zsh-autosuggestions $HOME/.zshrc) == '0' ]]; then
        sed -i "s/^plugins=(\(.*\))$/plugins=\(\1 zsh-autosuggestions\)/" $HOME/.zshrc
    fi

    if [[ ! -d "${zsh_plugin_path}/zsh-syntax-highlighting" ]]; then
        git clone https://gitee.com/imirror/zsh-autosuggestions.git ${zsh_plugin_path}/zsh-syntax-highlighting
    else
        echo "plugin zsh-syntax-highlighting is already installed."
    fi
    if [[ $(grep -c zsh-syntax-highlighting $HOME/.zshrc) == '0' ]]; then
        sed -i "s/^plugins=(\(.*\))$/plugins=\(\1 zsh-syntax-highlighting\)/" $HOME/.zshrc
    fi

    # export LANG=en_US.UTF-8
    sed -i "s/^# export LANG=en_US.UTF-8$/export LANG=en_US.UTF-8/" $HOME/.zshrc

    # export PATH=$HOME/bin:/usr/local/bin:$PATH
    # source $HOME/.bash_profile
    sed -i "s/^# export PATH=\$HOME\/bin:\/usr\/local\/bin:\$PATH$/export PATH=\$HOME\/bin:\/usr\/local\/bin:\$PATH\nsource \$HOME\/.bash_profile/" $HOME/.zshrc
    if [[ ! -f "$HOME/.bash_profile" ]]; then
        touch $HOME/.bash_profile
    fi

    if [[ -d "$HOME/.vim" ]]; then
        mv $HOME/.vim $HOME/.vim.env.bak
    fi
    ln -s $(pwd)/vim/.vim $HOME/.vim

    if [[ -f "$HOME/.vimrc" ]]; then
        mv $HOME/.vimrc $HOME/.vimrc.env.bak
    fi
    ln -s $(pwd)/vim/.vimrc $HOME/.vimrc

    return 0
}

setup_zsh
